import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

type CounterState = {
    value: number
}
type CounterAction = {
    type: string
    payload: number
}

const initialState: CounterState = {
    value: 0
}

export const counterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
        // Redux Toolkit 内置 Immer 库，可直接修改状态
        increment: (state: CounterState) => {
            state.value += 1
        },
        decrement: (state: CounterState) => {
            state.value -= 1
        },
        incrementByAmount: (state: CounterState, action: CounterAction) => {
            state.value += action.payload
        },
        decrementByAmount: (state: CounterState, action: CounterAction) => {
            state.value -= action.payload
        },
        reset: (state: CounterState) => {
            state.value = 0
        }
    }
})

// 创建异步thunk
export const fetchUser = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, { rejectWithValue }) => {
    try {
      const response = await fetch('https://api.github.com/users/1');
      const data = await response.json();
      return { userId, name: data.login };
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

// 导出 action 创建器
export const {
    increment,
    decrement,
    incrementByAmount,
    decrementByAmount,
    reset,
} = counterSlice.actions

// 导出切片 reducer
export default counterSlice.reducer
